package com.leecode.exercise;

public class 二分查找_01_排序数组 {

    public static void main(String[] args) {
        int[] sortedArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int target = 8;

        int result = binarySearch(sortedArray, target);

        if (result != -1) {
            System.out.println("元素 " + target + " 在数组中的索引是：" + result);
        } else {
            System.out.println("元素 " + target + " 不在数组中。");
        }
    }


    /**
     * 一次砍掉一半，找到返回对应下标，找不到返回-1
     *
     * @param array
     * @param target
     * @return
     */
    public static int binarySearch(int[] array, int target) {
        int left = 0;
        int right = array.length - 1;

        //大条件
        while (left <= right) {
            int mid = (left + right) / 2;
            //不断减半
            if (array[mid] == target) {
                return mid;
            }
            //在右边
            else if (array[mid] < target) {
                left = mid + 1;
            }

            //在左边
            else if (array[mid] > target) {
                right = mid - 1;
            }
        }
        return -1;
    }

}
